package DAO.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;

import DAO.TicketDAO;
import DAO.TrainDAO;

import model.impl.Passenger;
import model.impl.Ticket;
import model.impl.Train;

/**
 *  Implements TrainDAO interface, extend GenericDAOImpl class using as 
 *  parameters entity of Train and Integer class as an ID. It also adds some 
 *  specific to Train entity methods.
 */
public class TrainDAOImpl extends GenericDAOImpl<Train, Integer> implements
		TrainDAO {

	/**
	 * Checks given train and looks for all passengers that have tickets on
	 * it.
	 * 
	 * @param  train - Train entity where to look for passengers
	 * @return       - List of passengers on the given train or null if there 
	 * 				   is no passengers on train
	 */
	public List<Passenger> getAllPassangersOnTheTrain(Train train) {
		TicketDAO ticketDAO = new TicketDAOImpl();
		List<Passenger> passengers = null;
		passengers = new ArrayList<Passenger>();
		List<Ticket> passengersTicket = null;
		String sqlRequest = "SELECT t FROM Ticket t WHERE t.train = :givenTrain";
		Query query = this.getSession().createQuery(sqlRequest)
				.setParameter("givenTrain", train);
		passengersTicket = ticketDAO.findMany(query);
		if (passengersTicket != null) {
			for (int i = 0; i < passengersTicket.size(); i++) {
				passengers.add(passengersTicket.get(i).getPassenger());
			}
		}
		return passengers;
	}

	/**
	 * Looks for train with the instance Train.trainNumber equals to the
	 * given trainNumber parameter.
	 * 
	 * @param trainNumber - an Integer representing the Train.trainNumber 
	 * 						of the required train
	 * @return 			  - Train entity object or null if such object was
	 * 						not found
	 */
	public Train findTrainByTrainNumber(Integer trainNum) {
		Train train = null;
		String sqlRequest = "SELECT t FROM Train t WHERE t.trainNumber = :trainNum";
		Query query = this.getSession().createQuery(sqlRequest)
				.setParameter("trainNum", trainNum);
		train = findOne(query);
		
		return train;
	}
}
